<?php

/*
 +-----------------------------------------------------------------------+
 | plugins/sauserprefs/sauserprefs.inc                                   |
 |                                                                       |
 | This file is part of the RoundCube Webmail client                     |
 | Copyright (C) 2008-2009, RoundCube Dev. - Switzerland                 |
 | Licensed under the GNU GPL                                            |
 |                                                                       |
 | PURPOSE:                                                              |
 |	 Provide functionality for user spamassassin settings modification   |
 |                                                                       |
 +-----------------------------------------------------------------------+
 | Author: Philip Weir                                                   |
 +-----------------------------------------------------------------------+
 | Requires: plugins/sauserprefs/config.inc.php                          |
 +-----------------------------------------------------------------------+

 $Id: $

*/

require_once('plugins/sauserprefs/config.inc.php');

$OUTPUT->set_pagetitle(rcube_label('sauserprefssettings'));
$OUTPUT->add_handler('usersauserprefs', 'rcmail_sauserprefs_form');
$OUTPUT->include_script('sauserprefs.js');
$OUTPUT->add_label('spamaddressexists', 'spamenteraddress', 'spamaddresserror',
					'spamaddressdelete', 'enabled', 'disabled');
$OUTPUT->send('sauserprefs');

function rcmail_sauserprefs_form($attrib){
	global $sauserprefs_config;

	$blocks = $attrib['parts'] ? preg_split('/[\s,;]+/', strip_quotes($attrib['parts'])) : array('general','headers','tests','report','addresses');

	$user_db = new rcube_mdb2($sauserprefs_config['db_dsnw'], $sauserprefs_config['db_dsnr'], $sauserprefs_config['db_persistent']);
	$user_db->db_connect('r');

	// check DB connections and exit on failure
	if ($err_str = $user_db->is_error()) {
	  raise_error(array(
	    'code' => 603,
	    'type' => 'db',
	    'message' => $err_str), FALSE, TRUE);
	}

	// global settings
	$global_prefs = array();

	$sql_result = $user_db->query(
	  "SELECT ". $sauserprefs_config['sql_preference_field'] .", ". $sauserprefs_config['sql_value_field'] ."
	   FROM   ". $sauserprefs_config['sql_table_name'] ."
	   WHERE  ". $sauserprefs_config['sql_username_field'] ." = '\$GLOBAL'
	   AND    ". $sauserprefs_config['sql_preference_field'] ." <> 'whitelist_from'
	   AND    ". $sauserprefs_config['sql_preference_field'] ." <> 'blacklist_from'
	   AND    ". $sauserprefs_config['sql_preference_field'] ." <> 'whitelist_to';"
   	  );

	while ($sql_result && ($sql_arr = $user_db->fetch_assoc($sql_result)))
	    $global_prefs[$sql_arr[$sauserprefs_config['sql_preference_field']]] = $sql_arr[$sauserprefs_config['sql_value_field']];

	// user settings
	$user_prefs = array();

	$sql_result = $user_db->query(
	  "SELECT ". $sauserprefs_config['sql_preference_field'] .", ". $sauserprefs_config['sql_value_field'] ."
	   FROM   ". $sauserprefs_config['sql_table_name'] ."
	   WHERE  ". $sauserprefs_config['sql_username_field'] ." = '". $_SESSION['username'] ."'
	   AND    ". $sauserprefs_config['sql_preference_field'] ." <> 'whitelist_from'
	   AND    ". $sauserprefs_config['sql_preference_field'] ." <> 'blacklist_from'
	   AND    ". $sauserprefs_config['sql_preference_field'] ." <> 'whitelist_to';"
	  );

    while ($sql_result && ($sql_arr = $user_db->fetch_assoc($sql_result)))
	    $user_prefs[$sql_arr[$sauserprefs_config['sql_preference_field']]] = $sql_arr[$sauserprefs_config['sql_value_field']];

	$global_prefs = array_merge($sauserprefs_config['default_prefs'], $global_prefs);
	$user_prefs = array_merge($global_prefs, $user_prefs);

	list($form_start, $form_end) = get_form_tags($attrib, 'save-sauserprefs');
	unset($attrib['form']);

	$out = $form_start;

	foreach ($blocks as $part) {
		$out .= rcmail_sauserprefs_block($part, $global_prefs, $user_prefs, $attrib, $user_db);
	}

	return $out . $form_end;
}

function rcmail_sauserprefs_block($part, $global_prefs, $user_prefs, $attrib, $user_db) {
	global $RCMAIL, $OUTPUT, $sauserprefs_config;

	switch ($part)
	{
	// General tests
	case 'general':
		$table = new html_table(array('cols' => 2));

		if ($sauserprefs_config['general_settings']['score']) {
			$field_id = 'rcmfd_spamthres';
			$input_spamthres = new html_select(array('name' => '_spamthres', 'id' => $field_id));

			$decPlaces = 0;
			if ($sauserprefs_config['score_inc'] - (int)$sauserprefs_config['score_inc'] > 0)
				$decPlaces = strlen($sauserprefs_config['score_inc'] - (int)$sauserprefs_config['score_inc']) - 2;

			for ($i = 1; $i <= 10; $i = $i + $sauserprefs_config['score_inc'])
				$input_spamthres->add(number_format($i, $decPlaces), (float)$i);

			$table->add('title', html::label($field_id, Q(rcube_label('spamthres'))));
			$table->add(null, $input_spamthres->show((float)$user_prefs['required_hits']));

			$table->add(array('colspan' => 2), Q(rcube_label('spamthresexp')));
			$table->add_row();
		}

		if ($sauserprefs_config['general_settings']['subject']) {
			if ($sauserprefs_config['general_settings']['score']) {
				$table->add(null, "&nbsp;");
				$table->add(null, "&nbsp;");
			}

			$field_id = 'rcmfd_spamsubject';
			$input_spamsubject = new html_inputfield(array('name' => '_spamsubject', 'id' => $field_id, 'value' => $user_prefs['rewrite_header Subject'], 'style' => 'width:200px;'));

			$table->add('title', html::label($field_id, Q(rcube_label('spamsubject'))));
			$table->add(null, $input_spamsubject->show());

			$table->add(null, "&nbsp;");
			$table->add(null, Q(rcube_label('spamsubjectblank')));
		}

		if ($sauserprefs_config['general_settings']['language']) {
			if ($sauserprefs_config['general_settings']['subject'] || ($sauserprefs_config['general_settings']['score'] && !$sauserprefs_config['general_settings']['subject'])) {
				$table->add(null, "&nbsp;");
				$table->add(null, "&nbsp;");
			}

			$table->add('title', html::label($field_id, Q(rcube_label('spamlang'))));
			$table->add(null, "&nbsp;");
			$table->add(array('colspan' => 2), Q(rcube_label('spamlangexp')));
			$table->add_row();
			$table->add(null, "&nbsp;");
			$table->add(null, "&nbsp;");

			$select_all = html::a(array('href' => "#", 'onclick' => 'return select_all_langs()', 'title' => rcube_label('select') . " " . rcube_label('all')), rcube_label('all'));
			$select_none = html::a(array('href' => "#", 'onclick' => 'return select_no_langs()', 'title' => rcube_label('select') . " " . rcube_label('none')), rcube_label('none'));

			$table->add(array('colspan' => 2, 'id' => 'listcontrols'), rcube_label('select') .":&nbsp;". $select_all ."&nbsp;". $select_none);
			$table->add_row();

			if (!empty($attrib['enableicon']))
				$enable_button = html::img(array('src' => $attrib['enableicon'], 'alt' => rcube_label('enabled'), 'border' => 0));
			else
				$enable_button = rcube_label('enabled');

			if (!empty($attrib['disableicon']))
				$disable_button = html::img(array('src' => $attrib['disableicon'], 'alt' => rcube_label('disabled'), 'border' => 0));
			else
				$disable_button = rcube_label('disabled');

			$lang_table = new html_table(array('id' => 'spam-langs-table', 'class' => 'records-table', 'cellspacing' => '0', 'cols' => 2));
			$lang_table->add_header(array('colspan' => 2), rcube_label('language'));
			$lang_table->set_row_attribs(array('style' => 'display: none;'));
			$lang_table->add(array('id' => 'enable_button'), $enable_button);
			$lang_table->add(array('id' => 'disable_button'), $disable_button);

			if ($user_prefs['ok_locales'] == "all")
				$ok_locales = array_keys($sauserprefs_config['languages']);
			else
				$ok_locales = split(" ", $user_prefs['ok_locales']);

			$i = 0;
			foreach ($sauserprefs_config['languages'] as $lang_code => $name) {
				if (in_array($lang_code, $ok_locales)) {
					$action = rcube_label('enabled');
					$button = $enable_button;
				}
				else {
					$action = rcube_label('disabled');
					$button = $disable_button;
				}

				$button = html::a(array('id' => 'spam_lang_'.$i, 'href' => "#", 'onclick' => 'return message_lang("'.$lang_code.'", this)', 'title' => $action), $button);
				$input_spamlang = new html_checkbox(array('style' => 'display: none;', 'name' => '_spamlang[]', 'value' => $lang_code));

				$lang_table->add('lang', $name);
				$lang_table->add('tick', $button . $input_spamlang->show(in_array($lang_code, $ok_locales) ? $lang_code : ''));

				$i++;
			}

			$table->add(array('colspan' => 2), html::div(array('id' => 'spam-langs-cont'), $lang_table->show()));
			$table->add_row();
		}

		if ($table->size())
			$out = html::tag('fieldset', null, html::tag('legend', null, Q(rcube_label('spamgeneralsettings'))) . $table->show($attrib));

		break;

	// Header settings
	case 'headers':
		$data = Q(rcube_label('headersexp')) . "<br /><br />";
		$enable_block = new html_hiddenfield(array('name' => '_do_headers', 'value' => '1'));
		$data .= $enable_block->show();

		$field_id = 'rcmfd_spamfoldheaders';
		$input_spamreport = new html_checkbox(array('name' => '_spamfoldheaders', 'id' => $field_id, 'value' => '1'));
		$data .= $input_spamreport->show($user_prefs['fold_headers']) ."&nbsp;". html::label($field_id, Q(rcube_label('foldheaders'))) . "<br />";

		if ($user_prefs['remove_header all'] != 'Level') {
			$enabled = "1";
			$char = $user_prefs['add_header all Level'];
			$char = substr($char, 7, 1);
		}
		else {
			$enabled = "0";
			$char = "*";
		}

		$field_id = 'rcmfd_spamlevelstars';
		$input_spamreport = new html_checkbox(array('name' => '_spamlevelstars', 'id' => $field_id, 'value' => '1',
			'onchange' => 'toggle_level_char(this)'));
		$data .= $input_spamreport->show($enabled) ."&nbsp;". html::label($field_id, Q(rcube_label('spamlevelstars'))) . "<br />";

		$field_id = 'rcmfd_spamlevelchar';
		$input_spamsubject = new html_inputfield(array('name' => '_spamlevelchar', 'id' => $field_id, 'value' => $char,
			'style' => 'width:20px;', 'disabled' => $enabled?0:1));
		$data .= html::span(array('style' => 'padding-left: 30px;'), $input_spamsubject->show() ."&nbsp;". html::label($field_id, Q(rcube_label('spamlevelchar'))));

		$out = html::tag('fieldset', null, html::tag('legend', null, Q(rcube_label('headers'))) . $data);
		break;

	// Test settings
	case 'tests':
		$data = Q(rcube_label('spamtestssexp')) . "<br /><br />";
		$enable_block = new html_hiddenfield(array('name' => '_do_tests', 'value' => '1'));
		$data .= $enable_block->show();

		$field_id = 'rcmfd_spamuserazor1';
		$input_spamtest = new html_checkbox(array('name' => '_spamuserazor1', 'id' => $field_id, 'value' => '1'));
		$data .= $input_spamtest->show($user_prefs['use_razor1']) ."&nbsp;". html::label($field_id, Q(rcube_label('userazor1'))) . "<br />";

		$field_id = 'rcmfd_spamuserazor2';
		$input_spamtest = new html_checkbox(array('name' => '_spamuserazor2', 'id' => $field_id, 'value' => '1'));
		$data .= $input_spamtest->show($user_prefs['use_razor2']) ."&nbsp;". html::label($field_id, Q(rcube_label('userazor2'))) . "<br />";

		$field_id = 'rcmfd_spamusepyzor';
		$input_spamtest = new html_checkbox(array('name' => '_spamusepyzor', 'id' => $field_id, 'value' => '1'));
		$data .= $input_spamtest->show($user_prefs['use_pyzor']) ."&nbsp;". html::label($field_id, Q(rcube_label('usepyzor'))) . "<br />";

		$field_id = 'rcmfd_spamusebayes';
		$input_spamtest = new html_checkbox(array('name' => '_spamusebayes', 'id' => $field_id, 'value' => '1'));
		$data .= $input_spamtest->show($user_prefs['use_bayes']) ."&nbsp;". html::label($field_id, Q(rcube_label('usebayes'))) . "<br />";

		$field_id = 'rcmfd_spamusedcc';
		$input_spamtest = new html_checkbox(array('name' => '_spamusedcc', 'id' => $field_id, 'value' => '1'));
		$data .= $input_spamtest->show($user_prefs['use_dcc']) ."&nbsp;". html::label($field_id, Q(rcube_label('usedcc'))) . "<br />";

		if ($user_prefs['skip_rbl_checks'] == "1")
			$enabled = "0";
		else
			$enabled = "1";

		$field_id = 'rcmfd_spamskiprblchecks';
		$input_spamtest = new html_checkbox(array('name' => '_spamskiprblchecks', 'id' => $field_id, 'value' => '1'));
		$data .= $input_spamtest->show($enabled) ."&nbsp;". html::label($field_id, Q(rcube_label('skiprblchecks'))) . "<br />";

		$out = html::tag('fieldset', null, html::tag('legend', null, Q(rcube_label('spamtests'))) . $data);
		break;

	// Report settings
	case 'report':
		$data = Q(rcube_label('spamreport')) . "<br /><br />";
		$enable_block = new html_hiddenfield(array('name' => '_do_report', 'value' => '1'));
		$data .= $enable_block->show();

		$field_id = 'rcmfd_spamreport';
		$input_spamreport0 = new html_radiobutton(array('name' => '_spamreport', 'id' => $field_id.'_0', 'value' => '0'));
		$data .= $input_spamreport0->show($user_prefs['report_safe']) ."&nbsp;". html::label($field_id .'_0', Q(rcube_label('spamreport0'))) . "<br />";

		$input_spamreport1 = new html_radiobutton(array('name' => '_spamreport', 'id' => $field_id.'_1', 'value' => '1'));
		$data .= $input_spamreport1->show($user_prefs['report_safe']) ."&nbsp;". html::label($field_id .'_1', Q(rcube_label('spamreport1'))) . "<br />";

		$input_spamreport2 = new html_radiobutton(array('name' => '_spamreport', 'id' => $field_id.'_2', 'value' => '2'));
		$data .= $input_spamreport2->show($user_prefs['report_safe']) ."&nbsp;". html::label($field_id .'_2', Q(rcube_label('spamreport2'))) . "<br />";

		$out = html::tag('fieldset', null, html::tag('legend', null, Q(rcube_label('spamreportsettings'))) . $data);
		break;

	// Address settings
	case 'addresses':
		$data = Q(rcube_label('whitelistexp')) . "<br /><br />";
		$enable_block = new html_hiddenfield(array('name' => '_do_addresses', 'value' => '1'));
		$data .= $enable_block->show();

		if ($sauserprefs_config['whitelist_sync'])
			$data .= Q(rcube_label('autowhitelist')) . "<br /><br />";

		$table = new html_table(array('cols' => 3, 'width' => '100%'));
		$field_id = 'rcmfd_spamaddressrule';
		$input_spamaddressrule = new html_select(array('name' => '_spamaddressrule', 'id' => $field_id));
		$input_spamaddressrule->add(rcube_label('whitelist_from'),'whitelist_from');
		$input_spamaddressrule->add(rcube_label('blacklist_from'), 'blacklist_from');
		$input_spamaddressrule->add(rcube_label('whitelist_to'), 'whitelist_to');

		$field_id = 'rcmfd_spamaddress';
		$input_spamaddress = new html_inputfield(array('name' => '_spamaddress', 'id' => $field_id, 'style' => 'width:200px;'));

		$field_id = 'rcmbtn_add_address';
		$button_addaddress = new html_inputfield(array('type' => 'button', 'value' => rcube_label('addrule'), 'onclick' => 'addressrule_add()', 'id' => $field_id, 'class' => 'button', 'style' => 'width:75px;'));

		$table->add(null, $input_spamaddressrule->show());
		$table->add(null, $input_spamaddress->show());
		$table->add(array('align' => 'right'), $button_addaddress->show());
		$table->add(array('colspan' => 3), "&nbsp;");
		$table->add_row();

		if (!empty($attrib['deleteicon']))
			$del_button = html::img(array('src' => $RCMAIL->config->get('skin_path') . $attrib['deleteicon'], 'alt' => rcube_label('delete'), 'border' => 0));
		else
			$del_button = rcube_label('delete');

		$address_table = new html_table(array('id' => 'address-rules-table', 'class' => 'records-table', 'cellspacing' => '0', 'cols' => 3));
		$address_table->add_header(array('width' => '180px'), rcube_label('rule'));
		$address_table->add_header(null, rcube_label('email'));
		$address_table->add_header(array('width' => '40px'), '&nbsp;');

		address_row($address_table, null, null, $del_button);

		$sql_result = $user_db->query(
		  "SELECT ". $sauserprefs_config['sql_preference_field'] .", ". $sauserprefs_config['sql_value_field'] ."
		   FROM   ". $sauserprefs_config['sql_table_name'] ."
		   WHERE  ". $sauserprefs_config['sql_username_field'] ." = '". $_SESSION['username'] ."'
		   AND   (". $sauserprefs_config['sql_preference_field'] ." = 'whitelist_from'
		   OR     ". $sauserprefs_config['sql_preference_field'] ." = 'blacklist_from'
		   OR     ". $sauserprefs_config['sql_preference_field'] ." = 'whitelist_to')
		   ORDER BY ". $sauserprefs_config['sql_value_field'] .";"
		  );

		if ($sql_result && $user_db->num_rows($sql_result) > 0)
			$norules = 'display: none;';

		$address_table->set_row_attribs(array('style' => $norules));
		$address_table->add(array('colspan' => '3'), rep_specialchars_output(rcube_label('noaddressrules')));
		$address_table->add_row();
		$OUTPUT->set_env('address_rule_count', $user_db->num_rows());
		while ($sql_result && $sql_arr = $user_db->fetch_assoc($sql_result)) {
			$field = $sql_arr[$sauserprefs_config['sql_preference_field']];
			$value = $sql_arr[$sauserprefs_config['sql_value_field']];

			address_row($address_table, $field, $value, $del_button);
		}

		$table->add(array('colspan' => 3), html::div(array('id' => 'address-rules-cont'), $address_table->show()));
		$table->add_row();

		if ($table->size())
			$out = html::tag('fieldset', null, html::tag('legend', null, Q(rcube_label('spamaddressrules'))) . $data . $table->show($attrib));

		break;

	default:
		$out = '';
	}

	return $out;
}

function address_row($address_table, $field, $value, $del_button) {
	if (!isset($field))
		$address_table->set_row_attribs(array('style' => 'display: none;'));

	$hidden_action = new html_hiddenfield(array('name' => '_address_rule_act[]', 'value' => ''));
	$hidden_field = new html_hiddenfield(array('name' => '_address_rule_field[]', 'value' => $field));
	$hidden_text = new html_hiddenfield(array('name' => '_address_rule_value[]', 'value' => $value));

	switch ($field) {
		case "whitelist_from":
			$fieldtxt = rep_specialchars_output(rcube_label('whitelist_from'));
			break;
		case "blacklist_from":
			$fieldtxt = rep_specialchars_output(rcube_label('blacklist_from'));
			break;
		case "whitelist_to":
			$fieldtxt = rep_specialchars_output(rcube_label('whitelist_to'));
			break;
	}

	$address_table->add(array('class' => $field), $fieldtxt);
	$address_table->add(array('class' => 'email'), $value);
	$address_table->add('control', '&nbsp;' . html::a(array('href' => "#", 'onclick' => 'return addressrule_del(this)', 'title' => rcube_label('delete')), $del_button) . $hidden_action->show() . $hidden_field->show() . $hidden_text->show());

	return $address_table;
}

?>